<template>
  <div class="login-container" id="app">
    <h2>用户登录</h2>
    <form @submit.prevent="handleLogin">
      <div class="input-group">
        <label for="username">用户名：</label>
        <input
          type="text"
          id="username"
          name="username"
          placeholder="请输入用户名"
          required
          v-model="name"
        />
      </div>
      <div class="input-group">
        <label for="password">密码：</label>
        <input
          type="password"
          id="password"
          name="password"
          placeholder="请输入密码"
          required
          v-model="password"
        />
      </div>
      <button type="submit">登录</button>
      <p id="errorMessage" class="error-message">{{ errorMessage }}</p>
    </form>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { useRouter } from 'vue-router'

const router = useRouter()
// 定义响应式数据
const user = useUserStore()
const name = ref(user.name)
const password = ref('123456')
const errorMessage = ref('')
// const Vrouter = router()

onMounted(() => {
  // window.addEventListener('unload', saveSate)
})

function saveSate() {
  // window.sessionStorage.setItem('sate', JSON.stringify(this.$store.state.user))
}

// 登录处理函数
function handleLogin() {
  if (!name.value || !password.value) {
    errorMessage.value = '用户名和密码不能为空！'
    return
  }

  // 模拟登录验证
  if (name.value === name.value && password.value === password.value) {
    // alert('登录成功！')
    user.login(name.value, 25)
    router.push({ name: 'about' })
    // this.$router.push('/about')
    //存入登录人
    // window.sessionStorage.setItem('isLogin', true)
    // this.$store.dispatch('asyncUpdateUser', { name: this.name })
    // router.push('/about')
    errorMessage.value = ''
  } else {
    errorMessage.value = '用户名或密码错误，请重试！'
  }
}
</script>

<style>
/* 样式保持不变 */
body {
  font-family: Arial, sans-serif;
  background-color: #f4f4f4;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-container {
  background-color: #fff;
  padding: 20px 30px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  width: 300px;
  text-align: center;
}

h2 {
  margin-bottom: 20px;
  color: #333;
}

.input-group {
  margin-bottom: 15px;
  text-align: left;
}

label {
  display: block;
  margin-bottom: 5px;
  color: #555;
}

input[type='text'],
input[type='password'] {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

button:hover {
  background-color: #0056b3;
}

.error-message {
  color: red;
  margin-top: 10px;
  font-size: 14px;
}
</style>
